<?php

class User_Model_UserRow extends Zend_Db_Table_Row_Abstract
{
    public function sendActivationEmail()
    {
        if ($this->active) {
            return false;
        }
        
        $this->activation_key = $this->generateActivationKey(16);
        $this->save();
        
        // Don't send mails in the development enviroment
        if (APPLICATION_ENV == 'development') {
            return true;
        }
        
        $body = 'activation key: ' . $this->activation_key;

        $mail = new Zend_Mail();
        $mail->setBodyText($body)
            ->setFrom('no-reply@pldkp.no-ip.org', 'PLDKP Team')
            ->setReturnPath('no-reply@pldkp.no-ip.org')
            ->addTo($this->email, $this->handle)
            ->setSubject('PLDKP User Activation')
            ->send();
        
        return true;
    }
    
    protected function generateActivationKey($length = 10)
    {
        $keyset = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $randkey = "";
        for ($i = 0; $i < $length; $i++) {
            $randkey .= substr($keyset, rand(0,strlen($keyset)-1), 1);
        }
        return $randkey;    
    }
    
    public function activate($activationKey)
    {
        if ($this->active) {
            return false;
        }
        
        if ($this->activation_key == $activationKey) {
            $this->active = true;
            $this->activation_date = date("Y-m-d H:i:s", time());
            $this->save();
            return true;
        }
        
        return false;
        
    }
}
